<template>
    <div v-loading="loading" class="add">
        <SavePage :title="id ? '编辑养护记录' : '新增养护记录'">
            <template slot="buttons">
                <BaseButton :loading="submitLoading"  :disabled="submitDisabled" @click="handleSubmit">保存</BaseButton>
            </template>
            <template slot="body">
                <!-- 基础表单信息 -->
                <TitleTips title="基础信息" />
                <el-form ref="form" :model="form" :rules="rules" size="medium" label-width="88px">
                    <el-row :gutter="24">
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="项目名称">
                                <el-input disabled :value="form.projectName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="公路名称">
                                <el-input disabled :value="form.highwayName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="施工单位">
                                <el-input disabled :value="form.constructionUnitName"></el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="现场管理" prop="managementUnitId">
                                <OrgSelect :is-filter="false" :value.sync="form.managementUnitId" :name.sync="form.managementUnitName" clearable @change="form.inspectUsers = []" />
                            </el-form-item>
                        </el-col>
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="养护日期" prop="maintDate">
                                <el-date-picker
                                    v-model="form.maintDate"
                                    type="date"
                                    placeholder="请选择"
                                    format="yyyy-MM-dd"
                                    value-format="yyyy-MM-dd"
                                    style="width: 100%"
                                    :picker-options="pickerOptions"
                                />
                            </el-form-item>
                        </el-col>
                        
                        <el-col :xl="6" :lg="8">
                            <el-form-item label="任务来源" prop="taskSource">
                                <el-input v-model="form.taskSource" maxlength="50" show-word-limit clearable>
                                    <template slot="append">
                                        <span style="cursor: pointer;" @click="handleSelectOrder">选择任务单</span>
                                    </template>
                                </el-input>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="12" :lg="16">
                            <el-form-item label="类型" prop="type">
                                <el-radio-group v-model="form.type">
                                    <el-radio v-for="item in recordTypeOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
                                </el-radio-group>
                            </el-form-item>
                        </el-col>
                        <el-col :xl="12" :lg="16">
                            <el-form-item label="工作内容" prop="workContent">
                                <el-input
                                    v-model="form.workContent"
                                    type="textarea"
                                    placeholder="请输入"
                                    maxlength="100"
                                    :autosize="{ minRows: 1, maxRows: 4}"
                                    show-word-limit
                                >
                                </el-input>
                            </el-form-item>
                        </el-col>
                    </el-row>
                </el-form>
                <!-- 养护明细 -->
                <CardList :id="form.contractId" ref="cardListRef" :data="cardList"></CardList>
            </template>
        </SavePage>

        <OrderListDialog :id="form.constructionUnitId" ref="orderListDialog" :code="form.highwayCode" @success="getOrder"></OrderListDialog>
    </div>
</template>

<script>
import { MaintenanceRecordManagementModel } from '@/models'
import CardList from './CardList'
import OrderListDialog from './OrderListDialog'
import { RecordTypeOptions } from '@/views/maintenance-decision/constants'

export default {
    name: 'MaintenanceRecordAdd',
    components: {
        CardList,
        OrderListDialog
    },
    data() {
        return {
            model: new MaintenanceRecordManagementModel(),
            recordTypeOptions: RecordTypeOptions,
            loading: false,
            submitDisabled: false,
            submitLoading: false,
            id: '',
            // contractId: '',
            type: 'add',
            form: {
                managementUnitId: '',
                maintDate: '',
                type: '',
                taskSource: '',
                workContent: '',
            },
            cardList: [],
            pickerOptions: {
                disabledDate(time) {
                    return time.getTime() > Date.now() // 只允许选择今天或过去的时间
                }
            },
            rules: {
                managementUnitId: [{ required: true, message: '请选择', trigger: 'change' }],
                maintDate: [{ required: true, message: '请选择', trigger: 'change' }],
                type: [{ required: true, message: '请选择', trigger: 'change' }],
                taskSource: [{ required: true, message: '请输入', trigger: ['blur', 'change'] }],
                workContent: [{ required: true, message: '请输入', trigger: 'blur' }]
            },
        }
    },
    created() {
        this.getQuery()
        this.id && this.getDetail()
    },
    methods: {
        getOrder(data) {
            this.form.taskId = data.id
            this.form.taskSource = data.name
        },
        handleSelectOrder() {
            this.$refs['orderListDialog'].open()
        },
        getQuery() {
            const { type, id, contractId, highwayCode, highwayName, startStakeNo, endStakeNo, constructionUnitId, constructionUnitName, projectName } = this.$route.query
            this.id = id
            this.form.contractId = contractId
            this.form.highwayCode = highwayCode
            this.form.constructionUnitId = constructionUnitId
            this.form.highwayName = highwayName
            this.form.startStakeNo = startStakeNo
            this.form.endStakeNo = endStakeNo
            this.form.constructionUnitName = constructionUnitName
            this.form.projectName = projectName
            
            if (type === 'edit') {
                this.typeName = '编辑'
                this.loading = true
            } else {
                this.typeName = '新建'
            }
        },
        validNameUnique(rule, value, callback) {
            this.model.validNameUnique({ name: value, id: this.form.id || null }).then((res) => {
                if (!res) {
                    callback(new Error('合同名称已存在'))
                } else {
                    callback()
                }
            })
        },
        validCodeUnique(rule, value, callback) {
            this.model.validNameUnique({ code: value, id: this.form.id || null }).then((res) => {
                if (!res) {
                    callback(new Error('合同编号已存在'))
                } else {
                    callback()
                }
            })
        },
        handleLoad(value) {
            this.submitDisabled = value
        },
        getDetail() {
            this.model.detail({ id: this.id }).then(res => {
                this.form = res
                this.cardList = res.detailList || []
            }).finally(() => {
                this.loading = false
            })
        },
        handleSubmit() {
            this.submitLoading = true
            this.$refs['form'].validate(async valid => {
                if (valid) {
                    const validResult = await this.$refs['cardListRef'].validate()
                    console.log('validResult', validResult)
                    const detailList = this.$refs['cardListRef'].getData()
                    console.log('cardData', detailList)
                    if (validResult) {
                        console.log(this.form)
                        const data = {
                            ...this.form,
                            id: this.id,
                            contractId: this.form.contractId,
                            managementUnitId: this.form.managementUnitId[this.form.managementUnitId.length - 1],
                            detailList
                        }
                        this.model.saveOrUpdate(data).then(() => {
                            this.$message({
                                type: 'success',
                                message: '操作成功！',
                                duration: 500,
                                onClose: () => {
                                    this.$router.go(-1)
                                }
                            })
                        }).finally(() => {
                            this.submitLoading = false
                        })
                    } else {
                        this.submitLoading = false
                    }
                } else {
                    this.submitLoading = false
                }
            })
        }
    }
}
</script>

<style lang="scss" scoped>
.spe-item {
    ::v-deep {
        .el-form-item__label {
            text-align: center;
            padding: 0;
            &::before {
                display: none;
            }
        }
        .el-input,
        .el-input__inner {
            min-width: auto !important;
        }
    }
}

.add {
    width: 100%;
    // padding:0 20px
    .info {
        .sub-title {
            font-size: 14px;
            font-weight: 600;
        }
        .check-box {
            margin-top: 20px;
            .check-list {
                display: flex;
                justify-content: flex-start;
                align-items: center;
                flex-wrap: wrap;
                .check-item {
                    width: 33%;
                    margin: 4px 0;
                }
            }
        }
    }
}
</style>
